package com.glela.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glela.common.constant.BaseConstants;
import com.glela.common.util.DateUtil;
import com.glela.goods.model.request.ClassifyRequest;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.service.CategoryService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

@Controller
@RequestMapping(value = "classify", produces = "application/json;charset=UTF-8")
public class ClassifyController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(ClassifyController.class);
	
	@Autowired
	private CategoryService categoryService;
	@Autowired 
	private UserService userService;
	
	/**
	* **********************************************
	* @Title: goodsClassifyList 
	* @Description: 商品分类列表接口：返回1、2、3级分类，其中3级分类只显示分类下面存在商品信息，且is_show为1的分类
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月12日 上午10:59:28 
	* **********************************************
	 */
	@RequestMapping(value = "/goodsClassifyList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> goodsClassifyList(@RequestBody ClassifyRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			tempKey = StringUtils.EMPTY + DateUtil.currentYourDate("yyyy-MM-dd");
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				List<Map<String,Object>> goodsClassifyList = this.categoryService.goodsClassifyList();
				if (CollectionUtils.isEmpty(goodsClassifyList)) {
					rslt = toErrorModelJSON(ErrorEnum.C44001);
				} else {
					rslt = toResultModelJSON(goodsClassifyList);
				}
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			logger.error("商品分类列表异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 600));
	}
	
	/**
	* **********************************************
	* @Title: thirdGoodsClassifyList 
	* @Description: 三级分类接口：点击某个【三级分类】或者【更多】时调用，获取三级分类列表
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月12日 下午1:24:08 
	* **********************************************
	 */
	@RequestMapping(value = "/thirdGoodsClassifyList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> thirdGoodsClassifyList(@RequestBody ClassifyRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			tempKey = StringUtils.EMPTY + request.getId();
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				List<Map<String,Object>> thirdGoodsClassifyList = this.categoryService.thirdGoodsClassifyList(request.getId());
				if (CollectionUtils.isEmpty(thirdGoodsClassifyList)) {
					rslt = toErrorModelJSON(ErrorEnum.C44001);
				} else {
					rslt = toResultModelJSON(thirdGoodsClassifyList);
				}
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			logger.error("商品分类列表异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 600));
	}
	
	/**
	* **********************************************
	* @Title: thirdGoodsClassifyGoodsList 
	* @Description: 三级分类商品列表接口：根据上一个接口传递的三级分类ID，查询分类下的商品列表信息，列表按照销量（goods表对应的自动任务补充销量）正序排列
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月12日 下午1:24:08 
	* **********************************************
	 */
	@RequestMapping(value = "/thirdGoodsClassifyGoodsList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> thirdGoodsClassifyGoodsList(@RequestBody ClassifyRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getPageNum(),request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(request.getIds())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//店主用户ID
			Integer xzJJUserId = Integer.valueOf(BaseConstants.XZ_SISTER+"");
			// 店主用户ID  默认校妆姐姐店铺的店主ID
			Integer storeUserId = xzJJUserId;
			if (!ParameterUtils.validParams(request.getUserId())) {
				//登录人信息
				User user = this.userService.getUser(request.getUserId());
				if(user!=null&&user.getRecommendFrom()!=null){
					//店主身份ID
					String recommendFrom = user.getRecommendFrom();
					UserInfo userInfo = this.userService.selectUserInfoByPersionId(recommendFrom);
					if(userInfo!=null){
						storeUserId = Integer.parseInt(userInfo.getUserId()+"");
					}
				}
			}
			// 角色  默认为校妆姐姐
			String role = "MAJOR";
			if (storeUserId.intValue() != xzJJUserId.intValue()) {
				role = "GENERAL";
			}
			tempKey = StringUtils.EMPTY + role + "-" + request.getIds() + "-" + request.getPageNum() + "-" + request.getPageSize();
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				List<GoodsListResponse> thirdGoodsClassifyGoodsList = this.categoryService.thirdGoodsClassifyGoodsList(request.getIds(),storeUserId,request.getStartIndex(),request.getPageSize());
				if (CollectionUtils.isEmpty(thirdGoodsClassifyGoodsList)) {
					rslt = toResultModelJSON(new ResponsePageModel<GoodsListResponse>(thirdGoodsClassifyGoodsList.size(), request.getPageSize(), request.getPageNum(), new ArrayList<GoodsListResponse>()));//toErrorModelJSON(ErrorEnum.C44002);
				} else {
					rslt = toResultModelJSON(new ResponsePageModel<GoodsListResponse>(thirdGoodsClassifyGoodsList.size(), request.getPageSize(), request.getPageNum(), thirdGoodsClassifyGoodsList));
				}
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			logger.error("商品分类下的商品列表异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 120));
	}
	
}
